package com.indusfo.spc.client.service.impl;

import java.util.List;

import com.indusfo.spc.vo.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.indusfo.spc.client.mapper.ClientMatMapper;
import com.indusfo.spc.client.pojo.ClientMat;
import com.indusfo.spc.client.service.ClientMatService;
import com.indusfo.spc.exception.BusinessException;
import com.indusfo.spc.exception.ParamsErrorException;
import com.indusfo.spc.pojo.OrderBom;

/**
 * 客户端物料实现类
 * 
 * @author zhengd
 *
 */
@Service
public class ClientMatServiceImpl implements ClientMatService {
	@Autowired
	private ClientMatMapper clientMatMapper;

	/**
	 * 保存物料关联
	 */
	@Override
	@Transactional
	public Integer saveClientMat(ClientMat clientMat) {
		Integer count = clientMatMapper.saveClientMat(clientMat);
		if (count == 0) {
			throw new BusinessException("保存物料关联失败！");
		}
		count = clientMatMapper.saveClientMatlog(clientMat);
		if (count == 0) {
			throw new BusinessException("保存物料关联日志失败！");
		}
		return count;
	}

	/**
	 * 根据批号ID查询物料
	 */
	@Override
	public List<OrderBom> queryOrderBomByBatchId(ClientMat clientMat) {
		return clientMatMapper.queryOrderBomByBatchId(clientMat);
	}

	@Override
	public JSONObject queryMat(Integer matId) {
		return JSONObject.build(JSONObject.SUCCESS, "操作成功", clientMatMapper.queryMat(matId));
	}

	/**
	 * 物料替换，根据批号查询关键物料
	 */
	@Override
	public List<ClientMat> queryClientMatByBatchId(Integer batchId) {
		return clientMatMapper.queryClientMatByBatchId(batchId);
	}

	/**
	 * 清除物料绑定
	 */
	@Override
	public String deleteClientMat(ClientMat clientMat) {
		if (clientMat.getMatId() == null) {
			throw new ParamsErrorException("请传入物料ID");
		}
		if (clientMat.getBatchId() == null) {
			throw new ParamsErrorException("请传入批次ID");
		}
		Integer count = clientMatMapper.deleteClientMat(clientMat);
		if (count == 1) {
			return "解除绑定成功！";
		}
		return "解除绑定失败！";
	}

	/**
	 * 扫新物料保存
	 */
	@Override
	@Transactional
	public Integer updateClientMat(ClientMat clientMat) {
		if (clientMat.getClientMatId() == null) {
			throw new ParamsErrorException("请传入主键ID");
		}
		if (clientMat.getNewMatNo() == null) {
			throw new ParamsErrorException("请传入新批号");
		}
		Integer count = clientMatMapper.updateClientMat(clientMat);
		if (count == 0) {
			throw new BusinessException("保存物料关联失败！");
		}
		ClientMat clientMatlog = clientMatMapper.queryClientMat(clientMat.getClientMatId());
		clientMatlog.setUserId(clientMat.getUserId());
		clientMatlog.setStationId(clientMat.getStationId());
		clientMatlog.setMatNo(clientMat.getNewMatNo());
		clientMatlog.setProId(clientMat.getProId());
		count = clientMatMapper.saveClientMatlog(clientMatlog);
		if (count == 0) {
			throw new BusinessException("保存物料关联日志失败！");
		}
		return count;
	}
}
